package logger

import (
	"log/slog"
	"os"
	"path/filepath"
	"strings"
)

var lvl slog.LevelVar
var opts slog.HandlerOptions

func init() {
	lvl.Set(slog.LevelInfo)
	opts = slog.HandlerOptions{
		Level: &lvl,
	}
	slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, &opts)))
}

func SetOutputFile(filePath string) {
	dir := filepath.Dir(filePath)
	err := os.MkdirAll(dir, os.ModePerm)
	if err != nil {
		panic(err)
	}

	f, err := os.Create(filePath)
	if err != nil {
		panic(err)
	}

	logger := slog.New(slog.NewTextHandler(f, &opts))
	slog.SetDefault(logger)
}

func SetLevel(level string) {
	level = strings.ToUpper(level)
	switch level {
	case slog.LevelDebug.String():
		lvl.Set(slog.LevelDebug)
	case slog.LevelInfo.String():
		lvl.Set(slog.LevelInfo)
	case slog.LevelWarn.String():
		lvl.Set(slog.LevelWarn)
	case slog.LevelError.String():
		lvl.Set(slog.LevelError)
	}
}
